package com.faradel.pharmapp.managedbean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.apache.commons.lang.StringUtils;
import org.faradel.pharmapp.entities.PharmaUser;
import org.primefaces.event.SelectEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

import com.faradel.pharmapp.service.UserServiceInterface;

@ManagedBean
@RequestScoped
public class UserBean
{
    private PharmaUser user;
    private PharmaUser selectedUser;
    private PharmaUser currentUser;

    private String userId;

    // variable to render find data table
    private boolean renderTable;

    private List<PharmaUser> userList;

    private Map<String, Integer> jobs;

    private Map<String, Integer> providers;

    Map<String, String> searchMap = new HashMap<String, String>();

    {
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        currentUser = (PharmaUser) extContext.getSessionMap().get("sessionUser");

        user = getUserInstance();
        selectedUser = getUserInstance();

        providers = new HashMap<String, Integer>();
        providers.put("Faradel Pharmacy", 1);
        providers.put("St Luke's Clinic", 2);
        providers.put("Children's Mercy", 3);

        jobs = new HashMap<String, Integer>();
        jobs.put("Developer", 1);
        jobs.put("Pharmacist", 2);
        jobs.put("Cashier", 4);
        jobs.put("Pharmacy Tech", 3);
        jobs.put("External", 5);
    }

    /**
     * Get an instance of a pharma user
     * 
     * @return
     */
    private PharmaUser getUserInstance()
    {
        ApplicationContext context = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        return (PharmaUser) context.getBean("pharmaUser");
    }

    private UserServiceInterface getUserServiceImpl()
    {
        ApplicationContext context = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        return (UserServiceInterface) context.getBean("userServiceImpl");
    }

    public void createUser()
    {
        user.setLastModified(TimeClass.getCurrentDate());
        user.setUserLastModified(currentUser.getPharmaUserId());
        getUserServiceImpl().addUser(user);
        userId = String.valueOf(user.getPharmaUserId());
    }

    public void findUser()
    {
        userList = new ArrayList<PharmaUser>();

        if (StringUtils.isNotBlank(userId))
        {
            user.setPharmaUserId(Integer.valueOf(userId));
        }

        if (user.getPharmaUserId() > 0)
        {
            user = getUserServiceImpl().getUserById(user.getPharmaUserId());
            userList.add(user);
        }
        else if (checkAllValuesEmpty(user))
        {
            userList = getUserServiceImpl().getAllUsers();
        }
        else
        {
            userList = getUserServiceImpl().getByColumns(searchMap);
        }

        renderTable = true;
    }

    public String updateUser()
    {
        user.setLastModified(TimeClass.getCurrentDate());
        user.setUserLastModified(currentUser.getPharmaUserId());
        getUserServiceImpl().updateUser(user);
        return "userupdate";
    }

    public String deleteUser()
    {
        getUserServiceImpl().deleteUser(user);
        return "userdelete";
    }

    public void reset()
    {
        userId = null;
        user.setPharmaUserId(-1);
        user = null;
        userList = null;
    }

    public void rowSelectListener(SelectEvent event)
    {
        showPage();
    }

    private String showPage()
    {
        return "displayuser";
    }

    public String logout()
    {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

        return "index.jsf?faces-redirect=true";
    }

    public boolean isRenderTable()
    {
        return renderTable;
    }

    public void setRenderTable(boolean renderTable)
    {
        this.renderTable = renderTable;
    }

    public Map<String, String> getSearchMap()
    {
        return searchMap;
    }

    public void setSearchMap(Map<String, String> searchMap)
    {
        this.searchMap = searchMap;
    }

    private boolean checkAllValuesEmpty(PharmaUser user)
    {
        boolean retVal = true;
        if (StringUtils.isNotBlank(String.valueOf(user.getPharmaUserId())) && user.getPharmaUserId() > 0)
        {
            retVal = false;
            searchMap.put("PharmaUserId", String.valueOf(user.getPharmaUserId()));
        }
        if (StringUtils.isNotBlank(user.getFirstName()))
        {
            retVal = false;
            searchMap.put("firstName", user.getFirstName());
        }
        if (StringUtils.isNotBlank(user.getLastName()))
        {
            retVal = false;
            searchMap.put("lastName", user.getLastName());
        }
        if (StringUtils.isNotBlank(String.valueOf(user.getJobId())) && user.getJobId() > 0)
        {
            retVal = false;
            searchMap.put("jobId", String.valueOf(user.getJobId()));
        }
        if (StringUtils.isNotBlank(String.valueOf(user.getProviderId())) && user.getProviderId() > 0)
        {
            retVal = false;
            searchMap.put("providerId", String.valueOf(user.getProviderId()));
        }
        if (StringUtils.isNotBlank(user.getUserEmail()))
        {
            retVal = false;
            searchMap.put("userEmail", user.getUserEmail());
        }
        if (StringUtils.isNotBlank(user.getUserAddress()))
        {
            retVal = false;
            searchMap.put("userAddress", user.getUserAddress());
        }
        if (StringUtils.isNotBlank(user.getUserCity()))
        {
            retVal = false;
            searchMap.put("userCity", user.getUserCity());
        }
        if (StringUtils.isNotBlank(user.getUserState()))
        {
            retVal = false;
            searchMap.put("userState", user.getUserState());
        }
        if (StringUtils.isNotBlank(user.getUserCountry()))
        {
            retVal = false;
            searchMap.put("userCountry", user.getUserCountry());
        }
        if (StringUtils.isNotBlank(user.getUserPhone()))
        {
            retVal = false;
            searchMap.put("userPhone", user.getUserPhone());
        }
        if (StringUtils.isNotBlank(user.getUserZip()))
        {
            retVal = false;
            searchMap.put("userZip", user.getUserZip());
        }
        if (StringUtils.isNotBlank(user.getUserType()))
        {
            retVal = false;
            searchMap.put("userType", user.getUserType());
        }

        return retVal;
    }

    public PharmaUser getUser()
    {
        return user;
    }

    public void setUser(PharmaUser user)
    {
        this.user = user;
    }

    public List<PharmaUser> getUserList()
    {
        return userList;
    }

    public void setUserList(List<PharmaUser> userList)
    {
        this.userList = userList;
    }

    public PharmaUser getCurrentUser()
    {
        return currentUser;
    }

    public void setCurrentUser(PharmaUser currentUser)
    {
        this.currentUser = currentUser;
    }

    public Map<String, Integer> getJobs()
    {
        return jobs;
    }

    public void setJobs(Map<String, Integer> jobs)
    {
        this.jobs = jobs;
    }

    public Map<String, Integer> getProviders()
    {
        return providers;
    }

    public void setProviders(Map<String, Integer> providers)
    {
        this.providers = providers;
    }

    public String getUserId()
    {
        return userId;
    }

    public void setUserId(String userId)
    {
        this.userId = userId;
    }

    public PharmaUser getSelectedUser()
    {
        return selectedUser;
    }

    public void setSelectedUser(PharmaUser selectedUser)
    {
        this.selectedUser = selectedUser;
    }

}
